package t1;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class Client {
    private Selector selector;
    private static final int PORT = 9999;
    private SocketChannel sChannel;

    public Client() {
        try {
            selector = Selector.open();//创建选择器
            sChannel = SocketChannel.open();//连接服务器
            sChannel.configureBlocking(false);
            sChannel.connect(new InetSocketAddress("127.0.0.1",PORT));
            sChannel.register(selector, SelectionKey.OP_READ);
            System.out.println("客户端已经准备好");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) throws Exception {
        Client client = new Client();
        //定义一个线程专门负责监听发送来的消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        client.readInfo();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            client.sendToServer(line);
        }
    }

    private void sendToServer(String line) {
        try {
            sChannel.write(ByteBuffer.wrap(("username:"+line).getBytes()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void readInfo() throws IOException {
        if (selector.isOpen()) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isReadable()) {
                    SocketChannel sc = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    sc.read(buffer);
                    System.out.println(new String(buffer.array()).trim());
                }
                iterator.remove();
            }
        }
    }
}
